//
//  QNIDPadView.m
//  CreditCat
//
//  Created by rsh on 20120/8/27.
//  Copyright © 2020年 rsh. All rights reserved.
//

#import "QNIDPadView.h"

@interface QNIDPadView()<UITextFieldDelegate>

/**
 目标输入框
 */
@property (strong, nonatomic) UITextField *targetTextField;
@end

@implementation QNIDPadView{
    NSArray *_dataArray;
    NSInteger _count;
}

- (instancetype)initWithTargetTextField:(UITextField *)targetTextField{
    if (self = [super init]) {
        _targetTextField = targetTextField;
        //替换键盘
        targetTextField.inputView = self;
        _dataArray = [self p_createKeybordData];
        [self initNumberKeybordUIWithDataArray:_dataArray];
        self.frame = CGRectMake(0, 0, ScreenWidth, 219 /*247*/);
        _targetTextField.delegate = self;
//        [targetTextField becomeFirstResponder];
    }
    return self;
}

//展现键盘
-(void)show{
    if (self.targetTextField.isFirstResponder) {
        return;
    }
    [UIView animateWithDuration:0.25 animations:^{
        [self.targetTextField becomeFirstResponder];
    }];
}

//消失键盘
-(void)dimiss{
    if (!self.targetTextField.isFirstResponder) {
        return;
    }
    [UIView animateWithDuration:0.25 animations:^{
        [self.targetTextField resignFirstResponder];
    }];
}

//只能输入多少位
-(void)inputTextCount:(NSInteger)count
{
    _count = count;
}


#pragma mark - UI
- (void)initNumberKeybordUIWithDataArray:(NSArray<QNNumberPadModel*> *)dataArray{
    self.backgroundColor = [UIColor colorWithHexString:@"F3F3F3"];
    
//    UILabel *tipLabel = [[UILabel alloc] init];
//    [self addSubview:tipLabel];
//    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(@8);
//        make.centerX.equalTo(self.mas_centerX);
//    }];
//    tipLabel.textColor = [UIColor colorWithHexString:@"999999"];
//    tipLabel.font = [UIFont systemFontOfSize:12];
//    tipLabel.text = @"安全键盘";
    
    //键盘容器
    UIView *keybordContainerView = [[UIView alloc] init];
    [self addSubview:keybordContainerView];
    [keybordContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(tipLabel.mas_bottom).offset(8);
        make.top.left.right.bottom.equalTo(@0);
    }];
    keybordContainerView.backgroundColor = [UIColor clearColor];
    
    CGFloat const itemWidth = ScreenWidth/3.f;
    CGFloat const itemHeight = 219/4.f;
    
    //键盘布局
    for (int i = 0; i < dataArray.count; i ++) {
        UIButton *numberPadButton = [[UIButton alloc] init];
        [keybordContainerView addSubview:numberPadButton];
        CGFloat numberPadButtonX = i % 3 * itemWidth;
        CGFloat numberPadButtonY = i / 3 *itemHeight;

        numberPadButton.frame = CGRectMake(numberPadButtonX, numberPadButtonY, itemWidth, itemHeight);
        numberPadButton.backgroundColor = [UIColor whiteColor];
        QNNumberPadModel *model = dataArray[i];
        [numberPadButton setTitle:model.keybordNumber forState:UIControlStateNormal];
        [numberPadButton setTitleColor:[UIColor colorWithHexString:@"666666"] forState:UIControlStateNormal];
        numberPadButton.titleLabel.font = [UIFont systemFontOfSize:24];
        numberPadButton.tag = i;
        [numberPadButton addTarget:self action:@selector(didClickNumberButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    //删除按钮
    UIButton *deleteButton = [[UIButton alloc] init];
    [keybordContainerView addSubview:deleteButton];
    [deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(@0);
        make.width.equalTo(@(itemWidth));
        make.height.equalTo(@(itemHeight));
    }];
    [deleteButton setImage:[UIImage qn_imgWithCls:self.class podName:@"QNReuseTool" imgName:@"icon_kb_del"] forState:UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(didClickDeleteButton) forControlEvents:UIControlEventTouchUpInside];
    
    CGFloat const lineWidth = 1;
    //横线
    for (int i = 0; i < 3; i ++) {
        CGFloat horizontalLineViewX = 0;
        CGFloat horizontalLineViewY = i *itemHeight + itemHeight;
        UIView *horizontalLineView = [[UIView alloc] init];
        horizontalLineView.frame = CGRectMake(horizontalLineViewX, horizontalLineViewY, ScreenWidth, lineWidth);
        horizontalLineView.backgroundColor = [UIColor colorWithHexString:@"F3F3F3"];
        [keybordContainerView addSubview:horizontalLineView];
    }
    
    //纵线
    for (int i = 0; i < 2; i ++) {
        CGFloat verticalLineViewX = i *itemWidth + itemWidth;
        CGFloat verticalLineViewY = 0;
        UIView *verticalLineView = [[UIView alloc] init];
        verticalLineView.frame = CGRectMake(verticalLineViewX, verticalLineViewY, lineWidth, 219);
        verticalLineView.backgroundColor = [UIColor colorWithHexString:@"F3F3F3"];
        [keybordContainerView addSubview:verticalLineView];
    }
}
#pragma mark - target
- (void)didClickNumberButton:(UIButton *)button{
    QNNumberPadModel *model = _dataArray[button.tag];
    button.backgroundColor = [UIColor colorWithHexString:@"F3F3F3"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        button.backgroundColor = [UIColor whiteColor];
    });
    UITextRange *range = self.targetTextField.selectedTextRange;
    //确定光标位置
    NSInteger loc = [self.targetTextField offsetFromPosition:self.targetTextField.beginningOfDocument toPosition:self.targetTextField.selectedTextRange.start];
    
    //拼接字符串显示
    NSString *firstStr = [self.targetTextField.text substringToIndex:loc];
    NSString *secondStr = [self.targetTextField.text substringFromIndex:loc];
    self.targetTextField.text = [NSString stringWithFormat:@"%@%@%@",firstStr,model.secretNumberStr,secondStr];
    
    //输入完成后将光标保存在当前位置
    UITextPosition *start = [self.targetTextField positionFromPosition:range.end
                                                     inDirection:UITextLayoutDirectionRight
                                                          offset:1];
    if (start) {
        [self.targetTextField setSelectedTextRange:[self.targetTextField textRangeFromPosition:start toPosition:start]];
    }
    
    //代里传出
    if (_fyIDKeybordDelegate && [_fyIDKeybordDelegate respondsToSelector:@selector(fyIDKeybordView:clickIDNumberStr:)]) {
        [_fyIDKeybordDelegate fyIDKeybordView:self clickIDNumberStr:model.secretNumberStr];
    }
}

- (void)textFieldDidChangeSelection:(UITextField *)textField
{
    if (!_count) {
        _count = 1000000;
    }
    if (self.targetTextField.text.length >= _count) {
        self.targetTextField.text = [textField.text substringToIndex:_count];
    }
}


- (void)didClickDeleteButton{
    if (self.targetTextField.text.length > 0) {
        UITextRange *range = self.targetTextField.selectedTextRange;
        NSInteger loc = [self.targetTextField offsetFromPosition:self.targetTextField.beginningOfDocument toPosition:self.targetTextField.selectedTextRange.start];
        NSString *firstStr = [self.targetTextField.text substringToIndex:loc];
        NSString *secondStr = [self.targetTextField.text substringFromIndex:loc];
        //避免越界
        if (firstStr.length > 0) {
            //截取
            firstStr = [firstStr substringToIndex:firstStr.length - 1];
        }
        self.targetTextField.text = [NSString stringWithFormat:@"%@%@", firstStr, secondStr];
        
        //重新定位光标
        UITextPosition *start = [self.targetTextField positionFromPosition:range.start
                                                         inDirection:UITextLayoutDirectionLeft
                                                              offset:1];
        if (start) {
            [self.targetTextField setSelectedTextRange:[self.targetTextField textRangeFromPosition:start toPosition:start]];
        }

        if (_fyIDKeybordDelegate && [_fyIDKeybordDelegate respondsToSelector:@selector(clickDeleteButtonWithQNIDKeybordView:)]) {
            [self.fyIDKeybordDelegate clickDeleteButtonWithQNIDKeybordView:self];
        }
    }
}

- (NSArray <QNNumberPadModel *>*)p_createKeybordData{
    QNNumberPadModel *model1 = [[QNNumberPadModel alloc] initWithKeybordNumber:@"1"];
    QNNumberPadModel *model2 = [[QNNumberPadModel alloc] initWithKeybordNumber:@"2"];
    QNNumberPadModel *model3 = [[QNNumberPadModel alloc] initWithKeybordNumber:@"3"];
    
    QNNumberPadModel *model4 = [[QNNumberPadModel alloc] initWithKeybordNumber:@"4"];
    QNNumberPadModel *model5 = [[QNNumberPadModel alloc] initWithKeybordNumber:@"5"];
    QNNumberPadModel *model6 = [[QNNumberPadModel alloc] initWithKeybordNumber:@"6"];
    
    QNNumberPadModel *model7 = [[QNNumberPadModel alloc] initWithKeybordNumber:@"7"];
    QNNumberPadModel *model8 = [[QNNumberPadModel alloc] initWithKeybordNumber:@"8"];
    QNNumberPadModel *model9 = [[QNNumberPadModel alloc] initWithKeybordNumber:@"9"];
    
    QNNumberPadModel *modelX = [[QNNumberPadModel alloc] initWithKeybordNumber:@"X"];
    QNNumberPadModel *model0 = [[QNNumberPadModel alloc] initWithKeybordNumber:@"0"];
    return @[model1, model2, model3, model4, model5, model6, model7, model8, model9, modelX, model0];
}


@end

